package com.zsh.webfluxdemo1;

import com.zsh.webfluxdemo1.handler.UserHandler;
import com.zsh.webfluxdemo1.service.UserService;
import com.zsh.webfluxdemo1.service.impl.UserServiceImpl;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.netty.http.server.HttpServer;

import java.io.IOException;

import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RequestPredicates.accept;
import static org.springframework.web.reactive.function.server.RouterFunctions.toHttpHandler;

/**
 * @author zsh
 * @Description
 * @create 2022-03-08 9:16
 */
public class Server {

    public static void main(String[] args) throws IOException {
        Server server = new Server();
        server.createReactorServer();
        System.out.println("enter to quit");
        System.in.read();
    }

    //1 创建路由
    public RouterFunction<ServerResponse> routingFunction(){
        //创建handler对象
        UserService userService = new UserServiceImpl();
        UserHandler userHandler = new UserHandler(userService);

        //设置路由
       return RouterFunctions
               .route(GET("/user/{id}")  //路径设置
                        .and(accept(MediaType.APPLICATION_JSON))  //格式设置
                        , userHandler::getUserById)  //调用方法
               .andRoute(GET("/users")
                        .and(accept(MediaType.APPLICATION_JSON))
                        , userHandler::getAllUsers)


               ;
    }

    //3 创建服务器完成适配
    public void createReactorServer(){
        //路由和handler适配
        RouterFunction<ServerResponse> router = routingFunction();
        HttpHandler handler = toHttpHandler(router);

        ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(handler);

        //创建服务器
        HttpServer httpServer = HttpServer.create();
        httpServer.handle(adapter).bindNow();
    }
}
